package com.guaika.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guaika.reggie.common.ResultMessage;
import com.guaika.reggie.common.StringChars;
import com.guaika.reggie.dto.DishDto;
import com.guaika.reggie.entity.Category;
import com.guaika.reggie.entity.Dish;
import com.guaika.reggie.entity.DishFlavor;
import com.guaika.reggie.mapper.DishMapper;
import com.guaika.reggie.service.CategoryService;
import com.guaika.reggie.service.DishFlavorService;
import com.guaika.reggie.service.DishServices;
import com.guaika.reggie.utils.RedisCacheUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author GuaiKa
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishServices {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private RedisCacheUtils redisCacheUtils;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDishAndDishFlavor(DishDto dishDto) {
        //存入菜品信息
        this.save(dishDto);
        //获取菜品id
        Long id = dishDto.getId();
        //获取口味集合数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //将菜品id存入口味信息中
        flavors = flavors.stream().map(item->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        //批量插入
        dishFlavorService.saveBatch(flavors);
        //清理缓存
        redisCacheUtils.delete(redisCacheUtils.keys("dish_categroyId*"));
    }

    @Override
    public DishDto getByIdWidthDish(Long id) {
        //根据id获取菜品信息
        Dish dish = this.getById(id);
        //创建新的中间实体，保存多表数据
        DishDto dishDto = new DishDto();
        //复制数据
        BeanUtils.copyProperties(dish,dishDto);
        //创建查询
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        //将查询出来的口味数据集存入 flavors
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateWidthDishDto(DishDto dishDto) {
        //更新菜品信息
        this.updateById(dishDto);
        //根据菜品id，将已有的口味信息删除
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        //将菜品id赋值给对应的口味数据中
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //将修改好的集合对象进行批量插入
        dishFlavorService.saveBatch(flavors);
        //清理缓存
        redisCacheUtils.delete(redisCacheUtils.keys("dish_categroyId*"));
    }

    @Override
    public ResultMessage<List<DishDto>> dishlist(Dish dish) {
        List<DishDto> dtoList = null;
        String key = "dish_categroyId:"+dish.getCategoryId()+"status_"+dish.getStatus();
        dtoList = JSONObject.parseArray(redisCacheUtils.get(key), DishDto.class);
        if(dtoList!=null){
            return ResultMessage.success(dtoList);
        }
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据id和销售状态过滤
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId, dish.getCategoryId());
        dishLambdaQueryWrapper.eq(Dish::getIsDeleted,0);
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = this.list(dishLambdaQueryWrapper);
        dtoList = list.stream().map(item->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            LambdaQueryWrapper<DishFlavor> dtoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dtoLambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dtoLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        redisCacheUtils.setEx(key,JSONObject.toJSONString(dtoList),60, TimeUnit.MINUTES);
        return ResultMessage.success(dtoList);
    }

    @Override
    public ResultMessage<Page> dishPage(int page, int pageSize, String name) {
        Page<List<DishDto>> listPage = null;
        //定义分页查询redis 的 key
        String key = "dish_page:"+page+"pageSize:"+pageSize+"name:"+name;

        listPage = dishMapper.dishPage(new Page(page, pageSize), name);
        //存入redis
        redisCacheUtils.set(key, JSON.toJSONString(listPage));
        return ResultMessage.success(dishMapper.dishPage(new Page(page,pageSize), name));
    }

    @Override
    public ResultMessage<String> statusUpdate(Integer status,Long[] ids) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId,ids);
        Dish dish = new Dish();
        //判断起售停售
        if (status == 0) {
            dish.setStatus(0);
        } else {
            dish.setStatus(1);
        }
        boolean update = this.update(dish, wrapper);
        if(update){
            return ResultMessage.success(StringChars.UPDATE_SUCCESS.getStr());
        }
        //清理缓存
        redisCacheUtils.delete(redisCacheUtils.keys("dish_categroyId*"));
        return ResultMessage.error(StringChars.UPDATE_ERROR.getStr());
    }

    @Override
    public ResultMessage<String> deleteDish(Long[] ids) {
        int i = dishMapper.deleteByDishId(ids);
        if(i>0){
            //清理缓存
            redisCacheUtils.delete(redisCacheUtils.keys("dish_categroyId*"));
            return ResultMessage.success(StringChars.DELETE_SUCCESS.getStr());
        }
        return null;
    }
}
